import {Component, ElementRef, EventEmitter, Input, OnInit, Output, ViewChild} from '@angular/core';
import {ObjectUtil} from '../../../../utils/object-util';
import {ButtonSizeType, ButtonType} from '../../enums';
import {DhlCommonComponent} from '../../dhlCommonComponent';


/**
 * name: 按钮名字
 * type: {
 *     primary，
 *     default，
 *     danger，
 *     gray,
 *     link
 * }
 */
@Component({
  selector: 'dhl-button',
  templateUrl: './dhl-button.component.html'
})
export class DhlButtonComponent extends DhlCommonComponent implements OnInit {

  defaultClass = `${ButtonSizeType.DEFAULT}-button`;
  buttonClass = this.defaultClass;
  styleObj;
  checkedRow = [];
  importQueryBtn = [{}];
  @Input() checkAvailable = false;  // true: 只有当table行选中后按钮可以用， false：按钮一直都可以用
  @Input() queryParams = {};  // table的查询条件;
  @Input() dropdownMenu;
  @Input() loading = false;
  @Input() tipTitle;

  @Input() set width(v) {
    this.styleObj = {
      width: v
    };
  };

  tempType = 'primary';

  @Input() set type(value) {
    if (value == ButtonType.DEFAULT) {
      this.buttonClass = 'default-button ant-btn-default';
    } else {
      this.tempType = value;
    }
  };

  @Input() show = true;
  @Input() name;
  @Input() icon;
  @Input() onClick;  // click后的回调函数
  @Input() beforeCheck;  // click前的回调函数

  @Input()
  set sizeType(value) {
    this.buttonClass = this.buttonClass.replace(this.defaultClass, '') + ` ${value}-button`;
  }

  get sizeType() {
    return this.buttonClass;
  }

  @Input()
  set disabled(value) {
    this.buttonClass = value ? this.buttonClass + ' disable-button' : this.buttonClass.replace('disable-button', '');
  }

  get disabled() {
    return this.buttonClass.indexOf('disable-button') > -1 ? true : false;
  }

  @Output() buttonClick = new EventEmitter();
  @ViewChild('buttontag', {static: true, read: ElementRef}) dhlbuttontag: ElementRef;

  @ViewChild('linktag', {static: true, read: ElementRef}) linktag: ElementRef;


  ngOnInit() {
    const interval = setInterval(() => {
      const element = this.type == ButtonType.LINK ? this.linktag : this.dhlbuttontag;
      if (!ObjectUtil.isUndefined(element)) {
        const target = this.type == ButtonType.LINK ? $(element.nativeElement) : $('button', element.nativeElement);
        target.on('click', (e, params) => {
          const obj = {...params, checkedRow: this.checkedRow, queryParams: this.queryParams};
          this.buttonClick.emit(obj);
          if (this.onClick) {
            this.onClick(obj);
          }
        });
        clearInterval(interval);
      }
    }, 100);
  }

}














